package org.jeecgframework.web.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.tree.TreeNode;

import org.apache.log4j.Logger;
import org.apache.xmlbeans.impl.xb.xsdschema.RestrictionDocument.Restriction;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentTypeServiceI;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentTypeEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**
 * @Title: Controller
 * @Description: 设备类型
 * @author onlineGenerator
 * @date 2016-04-28 15:20:09
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyEquipmentTypeController")
public class ZyEquipmentTypeController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyEquipmentTypeController.class);


	@Autowired
	private ZyEquipmentTypeServiceI zyEquipmentTypeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;

	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 设备类型列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "zyEquipmentType")
	public ModelAndView zyEquipmentType(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_equipment_type/zyEquipmentTypeList");
	}

	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	@ResponseBody
	public List<TreeGrid> datagrid(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("equipmentType.id");
		}
		cq.add();
		List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType_id");
		treeGridModel.setParentText("equipmentType_typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}


	/**
	 * 设备类型新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd( HttpServletRequest req) {
		String parentId = oConvertUtils.getString(req.getParameter("parentId"));
		if(!parentId.equals("")){
			req.setAttribute("zyEquipmentTypePage", zyEquipmentTypeService.getEntity(ZyEquipmentTypeEntity.class, parentId));
		}
		return new ModelAndView("com/zybk/zy_equipment_type/zyEquipmentType-add");
	}

	/**
	 * 添加设备类型
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyEquipmentTypeEntity zyEquipmentType, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "设备类型添加成功";
		try{
			zyEquipmentTypeService.save(zyEquipmentType);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "设备类型添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 设备类型编辑页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyEquipmentTypeEntity zyEquipmentType, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEquipmentType.getId())) {
			zyEquipmentType = zyEquipmentTypeService.getEntity(ZyEquipmentTypeEntity.class, zyEquipmentType.getId());
			req.setAttribute("zyEquipmentTypePage", zyEquipmentType);
		}
		return new ModelAndView("com/zybk/zy_equipment_type/zyEquipmentType-update");
	}

	/**
	 * @author xiul
	 * 2016-4-27 下午5:00:42
	 * Description 设备模型验证规则 - 选择设备类型 
	 * @param request
	 * @return
	 */
	@RequestMapping(params="goChooseEquipmentType")
	public ModelAndView goChooseEquipmentType(HttpServletRequest request){
		return new ModelAndView("com/zybk/zy_equipment_type/zyChooseEquipmentType");
	}

	/**
	 * @author xiul
	 * 2016-4-27 下午5:04:08
	 * Description 设备模型验证规则 - 选择设备类型datagrid加载
	 * @param zyEquipmentTypeEntity
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params="dataGridOfChooseEquipmentType")
	@ResponseBody
	public List<TreeGrid> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity,HttpServletRequest request,HttpServletResponse response,TreeGrid treegrid){
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("equipmentType.id");
		}
		cq.add();
		List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType_id");
		treeGridModel.setParentText("equipmentType_typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}

	/**
	 * 更新设备类型
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyEquipmentTypeEntity zyEquipmentType, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "设备类型更新成功";
		ZyEquipmentTypeEntity t = zyEquipmentTypeService.get(ZyEquipmentTypeEntity.class, zyEquipmentType.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(zyEquipmentType, t);
			zyEquipmentTypeService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "设备类型更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * @author xiul
	 * 2016-6-27 上午10:15:43
	 * Description 检查设备机型 机型唯一性
	 * @param param 机型
	 * @param etId 更新时设备机型ID
	 * @param parentId 父ID
	 */
	@ResponseBody
	@RequestMapping(params="checkTypeDescUnique")
	public ValidForm checkTypeDescUnique(@RequestParam(value="param",defaultValue="")String param,
										 @RequestParam(value="etId",defaultValue="")String etId,
										 @RequestParam(value="parentId",defaultValue="")String parentId
	){
		ValidForm vf = new ValidForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total ");
		sql.append(" FROM zy_equipment_type et");
		sql.append(" WHERE ");
		sql.append(" et.type_desc = '"+param+"' ");
		if(StringUtil.isNotEmpty(parentId)){
			sql.append(" AND et.parent_id = '"+parentId+"' ");
		}
		if(StringUtil.isNotEmpty(etId)){
			sql.append(" AND et.id != '"+etId+"' ");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			vf.setStatus(ValidForm.N);
			vf.setInfo("当前机型已经存在");
		}
		return vf;
	}

	/**
	 * 删除设备类型
	 *
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ZyEquipmentTypeEntity zyEquipmentType, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, zyEquipmentType.getId());
		message = "设备类型删除成功";
		try{
			zyEquipmentTypeService.delete(zyEquipmentType);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "设备类型删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除设备类型
	 *
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "设备类型删除成功";
		try{
			for(String id:ids.split(",")){
				ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class,
						id
				);
				zyEquipmentTypeService.delete(zyEquipmentType);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "设备类型删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * @author xiul
	 * 2016-5-4 下午5:12:28
	 * Description  设备新增 修改页 选择设备 对应的机型
	 * @return
	 */
	@RequestMapping(params="goChooseEquipmentTypeForEquipment")
	public ModelAndView goChooseEquipmentTypeForEquipment(){
		return new ModelAndView("com/zybk/zy_equipment_type/zyChooseEquipmentTypeForEquipment");
	}

	/**
	 * @author xiul
	 * 2016-5-4 下午5:10:09
	 * Description 设备新增 修改页 选择设备 对应的机型 datagrid 
	 * @param request
	 * @param response
	 * @param treegrid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagridOfChooseEquipmentForEquipment")
	public List<TreeGrid> datagridOfChooseEquipmentForEquipment(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("equipmentType.id");
		}
		cq.add();
		List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType.id");
		treeGridModel.setParentText("equipmentType.typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}

	/**
	 * @author xiul
	 * 2016-5-4 下午5:10:09
	 * Description 设备新增 修改页 选择设备 对应的机型 datagrid
	 * @param request
	 * @param response
	 * @param treegrid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagridOfChooseEquipmentForEsItem")
	public List<TreeGrid> datagridOfChooseEquipmentForEsItem(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		CriteriaQuery cq;
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
		cq.notEq("typeDesc","设备");
		if (treegrid.getId() != null) {
			cq.eq("equipmentType.id", treegrid.getId());
		}else if(treegrid.getId() == null){
			cq.isNull("equipmentType.id");
		}
		cq.add();
		List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType.id");
		treeGridModel.setParentText("equipmentType.typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
		return treeGrids;
	}
	/**
	 * @author xiul
	 * 2016-6-30 上午10:23:38
	 * Description 巡检报告中 TMS品牌选择 和 服务器型号 选择 页面跳转
	 */
	@RequestMapping(params="goChooseEquipmentTypeForIr")
	public ModelAndView goChooseEquipmentTypeForIr(HttpServletRequest request){
		/*
		 * 1、只有 typeDesc 和 pTypeDesc 时查询的是以父级和父父级为条件所有当前级的集合
		 * 2、只有ppTypeDesc时 查询的是以父父级为条件所有当前级的集合
		 */
		String typeDesc = oConvertUtils.getString(request.getParameter("typeDesc"));//父级typeDesc
		String pTypeDesc = oConvertUtils.getString(request.getParameter("pTypeDesc"));//父父级typeDesc
		String ppTypeDesc = oConvertUtils.getString(request.getParameter("ppTypeDesc"));//父父级typeDesc
		String hidId = oConvertUtils.getString(request.getParameter("hidId"));
		String valId = oConvertUtils.getString(request.getParameter("valId"));
        System.out.println ( typeDesc+"-----------------" );
        System.out.println ( pTypeDesc+"-----------------" );
        System.out.println ( ppTypeDesc+"-----------------" );
        request.setAttribute("typeDesc", typeDesc);
		request.setAttribute("pTypeDesc", pTypeDesc);
		request.setAttribute("ppTypeDesc", ppTypeDesc);
		request.setAttribute("hidId", hidId);
		request.setAttribute("valId", valId);
		return new ModelAndView("com/zybk/zy_equipment_type/zyChooseEquipmentTypeForIr");
	}

	/**
	 * @author xiul
	 * 2016-6-30 上午10:27:57
	 * Description 巡检报告中 TMS品牌选择 和 服务器型号 选择 datagrid
	 */
	@ResponseBody
	@RequestMapping(params = "dataGridOfChooseEquipmentTypeForIr")
	public void dataGridOfChooseEquipmentTypeForIr(ZyEquipmentTypeEntity zyEsType,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try{
			request.setCharacterEncoding("utf-8");
			String typeDesc = oConvertUtils.getString(request.getParameter("typeDesc"));
			String pTypeDesc = oConvertUtils.getString(request.getParameter("pTypeDesc"));
			String ppTypeDesc = oConvertUtils.getString(request.getParameter("ppTypeDesc"));
			List<Map<String, Object>> resultMapList = new ArrayList<Map<String,Object>>();
			if(!typeDesc.equals("") && !pTypeDesc.equals("")){
				//根据 父级和 父父级 查询 父级是typeDesc 父父级是 pTypeDesc的子集
				resultMapList = zyEquipmentTypeService.queryEsTypeByPTypeDescAndPPTypeDesc(request,typeDesc,pTypeDesc);
			}
			if(!ppTypeDesc.equals("")){
				//根据父父级 typeDesc 查询子集
				resultMapList = zyEquipmentTypeService.queryEsTypeByPTypeDescAndPPTypeDesc(request,"",ppTypeDesc);
			}
			dataGrid.setResults(resultMapList);
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		TagUtil.datagrid(response, dataGrid);
	}

}
